var idDelMap = 0;

$(
	function ()
	{
		$("#addMapResult").hide();
		var name = $("#mapName"),
		allFields = $([]).add(name),
		tips = $("#validateTips");

		function updateTips(t) {
			tips.text(t).effect("highlight",{},1500);
		}

		function checkLength(o,n,min,max) {

			if ( o.val().length > max || o.val().length < min ) {
				o.addClass('ui-state-error');
				updateTips("Length of " + n + " must be between "+min+" and "+max+".");
				return false;
			} else {
				return true;
			}

		}

		function checkRegexp(o,regexp,n) {

			if ( !( regexp.test( o.val() ) ) ) {
				o.addClass('ui-state-error');
				updateTips(n);
				return false;
			} else {
				return true;
			}

		}

		$("#dialog").dialog({
			bgiframe: true,
			autoOpen: false,
			height: 200,
			modal: true,
			buttons: {
				'Create a map': function() {
					var bValid = true;
					allFields.removeClass('ui-state-error');

					bValid = bValid && checkLength(name,"mapName",3,16);

					bValid = bValid && checkRegexp(name,/^[a-z]([0-9a-z_])+$/i,"map may consist of a-z, 0-9, underscores, begin with a letter.");
					
					if (bValid) {
						$.get("index.php?action=mapAdd&mapname="+$(name).val(),
							function (data)
							{
								
								if (data.substr(0, 5) != "index")
								{
									updateTips(data);
									$(name).addClass('ui-state-error');
								} else {
									$('#dialog').dialog('close');
									window.location.href=data;
								}
							}
						);
						return false;
					}
				},
				Cancel: function() {
					$(this).dialog('close');
				}
			},
			close: function() {
				allFields.val('').removeClass('ui-state-error');
			}
		});
		
		$(function() {
			$("#dialogDel").dialog({
				bgiframe: true,
				resizable: false,
				autoOpen: false,
				height:200,
				modal: true,
				overlay: {
					backgroundColor: '#000',
					opacity: 0.5
				},
				buttons: {
					'Delete a map': function() {

					$("#delMapInfo").html("waiting ...");
						$.get("index.php?action=mapDel&mapid="+idDelMap,
							function (data)
							{
									$('#dialogDel').dialog('close');
									window.location.href=window.location.href;
							}
						);
					},
					Cancel: function() {
						$(this).dialog('close');
					}
				}
			});
		});

		
		$('#addMap').click(function() {
			allFields.removeClass('ui-state-error');
			tips.text('');
			$('#dialog').dialog('open');
			return false;
		});

		
	}
);

function delMap(idDel, messageDel)
{
	idDelMap = idDel;
	$("#delMapInfo").html(messageDel+" ?");
	$("#dialogDel").dialog('open');
	return false;
}